<template>
  <div>
    <Breadcrumb></Breadcrumb>
    <PageDetailLayout
      @formCancel="genCommFormCancel"
      @formSubmit="genCommFormSubmit">
      <el-form
        v-loading="genCommFormLoading"
        :ref="genCommFormRef"
        :model="genCommForm"
        :rules="genCommFormRules"
        size="small"
        label-width="120px">
        <el-form-item label="设备类别" prop="deviceType">
          <el-select v-model="genCommForm.deviceType" clearable filterable
                     class="width-100" placeholder="请选择设备类别" @change="deviceTypeChanged">
            <el-option :label="deviceType.label" :value="deviceType.value" :key="idx"
                       v-for="(deviceType, idx) in deviceTypeData"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="命令方法名" prop="methodName">
          <el-select v-model="genCommForm.methodName" clearable filterable
                     class="width-100" placeholder="请选择命令方法名"
                     @change="methodNameChanged">
            <el-option-group
              v-for="(group, idx) in genFuncData"
              :key="idx"
              :label="group.label">
              <el-option
                v-for="(item, idx) in group.options"
                :key="idx"
                :label="item.name"
                :value="item.name">
                <span>{{item.name}}</span>
                <span class="mar-lft font-color-warning">{{item.alias || ''}}</span>
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="命令类型" prop="generalCommandType">
          <el-radio-group v-model="genCommForm.generalCommandType">
            <el-radio :label="type.value" :key="idx"
                      v-for="(type, idx) in commonConfig.commandType">{{type.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="命令别名" prop="methodAlias">
          <el-input v-model="genCommForm.methodAlias" placeholder="请填写命令别名"></el-input>
        </el-form-item>
        <el-form-item label="下发参数">
          <GenCommParams title="下发" type="req" :device-type="genCommForm.deviceType"
                         :param-map-data="controlParamsData"></GenCommParams>
        </el-form-item>
        <el-form-item label="响应参数">
          <GenCommParams title="上报" type="resp" :device-type="genCommForm.deviceType"
                         :param-map-data="statusParamsData"></GenCommParams>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="genCommForm.remarks" placeholder="请填写备注"></el-input>
        </el-form-item>
      </el-form>
    </PageDetailLayout>
  </div>
</template>

<script>
  import {commonConfig} from "@/config/common";
  import {commonString, msgCode} from "@/config/string";
  import {routerMeta} from "@/router/routerMeta";
  import {messageHandle, deepCopyWithJson} from "@/utils";
  import EnumDynamic from "@/components/EnumDynamic";
  import GenCommParams from './partial/GenCommParams';

  export default {
    name: "GeneralCommandAdd",
    components: {
      EnumDynamic, GenCommParams
    },
    data() {
      return {
        commonConfig: commonConfig,
        genCommFormLoading: false,
        genCommForm: {},
        genCommFormRules: {
          deviceType: [
            {required: true, message: '请选择设备类别', trigger: 'blur'}
          ],
          methodName: [
            {required: true, message: '请填写命令方法名', trigger: 'blur'}
          ],
          generalCommandType: [
            {required: true, message: '请选择命令类型', trigger: 'blur'}
          ],
          methodAlias: [
            {required: true, message: '请填写命令别名', trigger: 'blur'}
          ],
        },
        genCommFormRef: 'genCommFormRef',
        deviceTypeData: [],
        genFuncData: [],
        statusParamsData: [],
        controlParamsData: [],
        protocolId:''
      }
    },
    activated() {
      this.initGenCommForm();
      this.getDeviceTypeData();
      this.protocolId = this.$route.query.protocolId;
      this.genCommForm.deviceType = this.$route.query.deviceType;
      if(this.genCommForm.deviceType){
        this.deviceTypeChanged()
      }
    },
    methods: {
      initGenCommForm() {
        this.genCommForm = {
          deviceType: '',
          methodName: '',
          generalCommandType: commonConfig.commandType[0].value,
          methodAlias: '',
          remarks: '',
        };
        this.statusParamsData = [];
        this.controlParamsData = [];
      },
      resetGenCommForm() {
        this.initGenCommForm();
        const genCommForm = this.$refs[this.genCommFormRef];
        genCommForm && genCommForm.resetFields();
      },
      getDeviceTypeData() {
        API.deviceType.deviceTypeAll().then(result => {
          const {data = []} = result;
          this.deviceTypeData = data;
        });
      },
      getGenFuncData() {
        const param = {deviceType: {$in: [this.genCommForm.deviceType, '00']}};
        API.genFunc.genFuncAll(param).then(result => {
          const {data = []} = result;
          this.genFuncData = [];
          const initGenFuncData = [{label: '通用', value: 2, options: []}];
          deepCopyWithJson(commonConfig.commandType).forEach(ct => {
            initGenFuncData.push({label: ct.label, value: ct.value, options: []});
          });
          data.forEach(d => {
            if (d.deviceType === '00') {
              initGenFuncData[0].options.push(d);
            } else {
              initGenFuncData[d.type].options.push(d);
            }
          });

          initGenFuncData.forEach(gc => {
            const {options = []} = gc;
            options.length && (this.genFuncData.push(gc));
          });
        }).catch(err => {
          console.log('err', err)
        });
      },
      deviceTypeChanged() {
        this.genCommForm.methodName = '';
        this.genCommForm.methodAlias = '';
        this.statusParamsData = [];
        this.controlParamsData = [];
        this.getGenFuncData();
      },
      methodNameChanged() {
        // option 数据转换，适配选择框
        let flatGenFuncData = [];
        this.genFuncData.forEach(gf => {
          flatGenFuncData = _.union(flatGenFuncData, gf.options || [])
        });
        const selFunc = flatGenFuncData.find(gf => {
          return gf.name === this.genCommForm.methodName
        }) || {};
        // 将选择后的值 加入表单
        this.genCommForm.generalCommandType = selFunc.type || '';
        this.genCommForm.methodAlias = selFunc.alias || '';
      },
      genCommFormCancel() {
        if(this.$route.query.protocolId && this.$route.query.deviceType){
          this.$router.go(-1)
        }else{
          this.$router.push({name: routerMeta.generalCommand.name});
        }
      },
      genCommFormSubmit() {
        this.$refs[this.genCommFormRef].validate((valid) => {
          if (!valid) return;
          const params = {
            ...this.genCommForm,
            generalProtocolId:this.protocolId?this.protocolId:'',
            statusParams: this.statusParamsData.map((sp, idx) => {
              return {...sp, sort: idx};
            }),
            controlParams: this.controlParamsData.map((cp, idx) => {
              return {...cp, sort: idx};
            }),
            examineStatus: false
          };
          this.genCommFormLoading = true;
          API.genCommand.genCommAdd(params).then(result => {
            messageHandle({code: msgCode.ADD_SUCCESS, title: '通用命令'});
            this.genCommFormLoading = false;
            this.resetGenCommForm();
            if(this.$route.query.protocolId && this.$route.query.deviceType){
              this.$router.go(-1)
            }else{
              this.$router.push({name: routerMeta.generalCommand.name});
            }

          }).catch(err => {
            console.log('err', err)
            this.genCommFormLoading = false;
          });
        });
      },
    },
  }
</script>

<style scoped>

</style>
